package com.itjin.health.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itjin.health.domain.dto.FeedbackAddRequest;
import com.itjin.health.domain.dto.FeedbackQueryRequest;
import com.itjin.health.domain.dto.FeedbackUpdateRequest;
import com.itjin.health.domain.entity.User;
import com.itjin.health.domain.entity.UserFeedback;
import com.itjin.health.domain.vo.FeedbackVO;
import com.itjin.health.exception.BusinessException;
import com.itjin.health.exception.ErrorCode;
import com.itjin.health.mapper.UserFeedbackMapper;
import com.itjin.health.mapper.UserMapper;
import com.itjin.health.service.UserFeedbackService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户反馈服务实现
 */
@Service
@Slf4j
public class UserFeedbackServiceImpl extends ServiceImpl<UserFeedbackMapper, UserFeedback>
    implements UserFeedbackService {

  @Resource
  private UserMapper userMapper;

  /**
   * 添加反馈
   *
   * @param addRequest 添加请求
   * @param userId     用户ID
   * @return 反馈ID
   */
  @Override
  public Integer addFeedback(FeedbackAddRequest addRequest, Integer userId) {
    // 参数校验
    if (addRequest == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    if (userId == null || userId <= 0) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    if (StringUtils.isBlank(addRequest.getContent())) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "反馈内容不能为空");
    }
    if (StringUtils.isBlank(addRequest.getFeedbackType())) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "反馈类型不能为空");
    }

    // 创建反馈对象
    UserFeedback feedback = new UserFeedback();
    BeanUtils.copyProperties(addRequest, feedback);
    feedback.setUserId(userId);
    feedback.setStatus("待处理"); // 默认状态为待处理

    // 保存到数据库
    boolean result = this.save(feedback);
    if (!result) {
      throw new BusinessException(ErrorCode.SYSTEM_ERROR, "反馈提交失败");
    }

    return feedback.getId();
  }

  /**
   * 删除反馈
   *
   * @param id     反馈ID
   * @param userId 用户ID
   * @return 是否成功
   */
  @Override
  public boolean deleteFeedback(Integer id, Integer userId) {
    // 参数校验
    if (id == null || id <= 0 || userId == null || userId <= 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    // 查询反馈是否存在
    UserFeedback feedback = this.getById(id);
    if (feedback == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "反馈不存在");
    }

    // 校验是否为反馈作者（只有自己的反馈才能删除，管理员另外处理）
    if (!feedback.getUserId().equals(userId)) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权删除他人反馈");
    }

    // 删除反馈
    return this.removeById(id);
  }

  /**
   * 更新反馈
   *
   * @param updateRequest 更新请求
   * @param userId        用户ID
   * @return 是否成功
   */
  @Override
  public boolean updateFeedback(FeedbackUpdateRequest updateRequest, Integer userId) {
    // 参数校验
    if (updateRequest == null || updateRequest.getId() == null || updateRequest.getId() <= 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    if (userId == null || userId <= 0) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }

    // 查询反馈是否存在
    Integer feedbackId = updateRequest.getId();
    UserFeedback oldFeedback = this.getById(feedbackId);
    if (oldFeedback == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "反馈不存在");
    }

    // 校验是否为反馈作者（只有自己的反馈才能更新，管理员另外处理）
    if (!oldFeedback.getUserId().equals(userId)) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权修改他人反馈");
    }

    // 更新反馈信息
    UserFeedback feedback = new UserFeedback();
    BeanUtils.copyProperties(updateRequest, feedback);
    feedback.setId(feedbackId);
    feedback.setUserId(userId);

    return this.updateById(feedback);
  }

  /**
   * 根据ID获取反馈
   *
   * @param id 反馈ID
   * @return 反馈视图对象
   */
  @Override
  public FeedbackVO getFeedbackById(Integer id) {
    // 参数校验
    if (id == null || id <= 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    // 查询反馈
    UserFeedback feedback = this.getById(id);
    if (feedback == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "反馈不存在");
    }

    // 转换为VO对象
    FeedbackVO feedbackVO = new FeedbackVO();
    BeanUtils.copyProperties(feedback, feedbackVO);

    // 获取用户名
    User user = userMapper.selectById(feedback.getUserId());
    if (user != null) {
      feedbackVO.setUsername(user.getUsername());
    }

    return feedbackVO;
  }

  /**
   * 分页获取当前用户的反馈列表
   *
   * @param queryRequest 查询请求
   * @param userId       用户ID
   * @return 反馈列表分页结果
   */
  @Override
  public Page<FeedbackVO> listUserFeedbacks(FeedbackQueryRequest queryRequest, Integer userId) {
    // 参数校验
    if (queryRequest == null || userId == null || userId <= 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    // 构建查询条件
    QueryWrapper<UserFeedback> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("user_id", userId);

    // 添加过滤条件
    addQueryCondition(queryWrapper, queryRequest);

    // 排序
    queryWrapper.orderByDesc("created_at");

    // 分页查询
    Page<UserFeedback> feedbackPage = this.page(
        new Page<>(queryRequest.getCurrent(), queryRequest.getPageSize()),
        queryWrapper);

    // 转换为VO对象
    return convertToVOPage(feedbackPage);
  }

  /**
   * 分页获取所有反馈（管理员使用）
   *
   * @param queryRequest 查询请求
   * @return 反馈列表分页结果
   */
  @Override
  public Page<FeedbackVO> listAllFeedbacks(FeedbackQueryRequest queryRequest) {
    // 参数校验
    if (queryRequest == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    // 构建查询条件
    QueryWrapper<UserFeedback> queryWrapper = new QueryWrapper<>();

    // 添加过滤条件
    addQueryCondition(queryWrapper, queryRequest);

    // 排序
    queryWrapper.orderByDesc("created_at");

    // 分页查询
    Page<UserFeedback> feedbackPage = this.page(
        new Page<>(queryRequest.getCurrent(), queryRequest.getPageSize()),
        queryWrapper);

    // 转换为VO对象
    return convertToVOPage(feedbackPage);
  }

  /**
   * 添加查询条件
   * 
   * @param queryWrapper 查询包装器
   * @param queryRequest 查询请求
   */
  private void addQueryCondition(QueryWrapper<UserFeedback> queryWrapper, FeedbackQueryRequest queryRequest) {
    // 反馈类型
    if (StringUtils.isNotBlank(queryRequest.getFeedbackType())) {
      queryWrapper.eq("feedback_type", queryRequest.getFeedbackType());
    }

    // 处理状态
    if (StringUtils.isNotBlank(queryRequest.getStatus())) {
      queryWrapper.eq("status", queryRequest.getStatus());
    }

    // 关键词搜索
    if (StringUtils.isNotBlank(queryRequest.getKeyword())) {
      queryWrapper.like("content", queryRequest.getKeyword());
    }
  }

  /**
   * 将实体分页转换为VO分页
   * 
   * @param feedbackPage 实体分页
   * @return VO分页
   */
  private Page<FeedbackVO> convertToVOPage(Page<UserFeedback> feedbackPage) {
    List<UserFeedback> feedbackList = feedbackPage.getRecords();
    List<FeedbackVO> feedbackVOList = new ArrayList<>();

    // 批量查询用户
    List<Integer> userIds = new ArrayList<>();
    for (UserFeedback feedback : feedbackList) {
      userIds.add(feedback.getUserId());
    }

    // 没有记录则直接返回
    if (userIds.isEmpty()) {
      Page<FeedbackVO> page = new Page<>(feedbackPage.getCurrent(), feedbackPage.getSize(), feedbackPage.getTotal());
      page.setRecords(feedbackVOList);
      return page;
    }

    // 查询用户信息
    QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
    userQueryWrapper.in("id", userIds);
    List<User> users = userMapper.selectList(userQueryWrapper);

    // 构建用户ID到用户名的映射
    java.util.Map<Integer, String> userIdToNameMap = new java.util.HashMap<>();
    for (User user : users) {
      userIdToNameMap.put(user.getId(), user.getUsername());
    }

    // 转换为VO对象
    for (UserFeedback feedback : feedbackList) {
      FeedbackVO feedbackVO = new FeedbackVO();
      BeanUtils.copyProperties(feedback, feedbackVO);

      // 设置用户名
      feedbackVO.setUsername(userIdToNameMap.getOrDefault(feedback.getUserId(), "未知用户"));

      feedbackVOList.add(feedbackVO);
    }

    // 构建VO分页对象
    Page<FeedbackVO> voPage = new Page<>(feedbackPage.getCurrent(), feedbackPage.getSize(), feedbackPage.getTotal());
    voPage.setRecords(feedbackVOList);

    return voPage;
  }
}